package com.szt.sy.controller.base;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.szt.sy.config.ApplicationConfig;
import com.szt.sy.exception.ApplicationRuntimeException;
import com.szt.sy.util.img.ImgUtils;
import com.szt.sy.util.web.FileUpload;
import com.szt.sy.vo.rep.base.RepBaseVO;

/***
 * 接口-基类-controller
 * 
 * @author wwy
 *
 */
public class ApiBaseController extends BaseController {
	
	@Autowired
	private ApplicationConfig applicationConfig;
	
	/***
	 * 处理api异常
	 *
	 * @param ex
	 * @param request
	 * @param response
	 * @return
	 */
	@ExceptionHandler(value = { ApplicationRuntimeException.class })
	@ResponseBody
	public RepBaseVO apiException(Exception ex, HttpServletRequest request, HttpServletResponse response) {
		
		RepBaseVO repVO = new RepBaseVO<>();
		logger.error("操作异常:", ex);
		return repVO.setCommonFail().setMes(ex.getMessage());
	}
	
	/***
	 * 处理通用异常
	 *
	 * @param ex
	 * @param request
	 * @param response
	 * @return
	 */
	@ExceptionHandler(value = { Exception.class })
	@ResponseBody
	public RepBaseVO exp(Exception ex, HttpServletRequest request, HttpServletResponse response) {
		RepBaseVO repVO = new RepBaseVO<>();
		logger.error("操作异常:", ex);
		return repVO.setCommonFail().setMes("系统繁忙");
	}
	
	/***
	 * 判断参数不能为空
	 *
	 * @param objects
	 * @return
	 */
	public boolean notEmpty(Object... objects) {
		for (Object object : objects) {
			if (object instanceof String) {
				if (StringUtils.isBlank((String) object)) {
					return false;
				}
			} else {
				if (object == null) {
					return false;
				}
			}
		}
		return true;
	}
	
	/***
	 * 上传文件
	 *
	 * @param file
	 * @return
	 */
	protected String uploadFile(MultipartFile multipartFile) {
		String fileName = FileUpload.fileUp(multipartFile, applicationConfig.getUploadFileLocation(),
				IdWorker.getId() + "");
		
		String filePath = applicationConfig.getUploadFileLocation() + fileName;
		File file = new File(filePath);
		Long fileSize = multipartFile.getSize();
		// 压缩
		if (fileSize > 600 * 1024) {
			double quailty = 1;
			if (fileSize < 1000 * 1024) {
				quailty = 0.8;
			} else if (fileSize < 2000 * 1024) {
				quailty = 0.7;
			} else {
				quailty = 0.65;
			}
			ImgUtils.compressFile1(file, quailty, filePath);
		}
		return applicationConfig.getFileServerPrefix() + fileName;
	}
	
}
